import { useCounter } from '@vueuse/core';
import { computed, ref } from 'vue';

export interface CountdownOptions {
  seconds?: number;
  onComplete?: () => void;
}

export const useCountdown = (options: CountdownOptions = {}) => {
  const {
    seconds = 60,
    onComplete,
  } = options;

  const isRunning = ref(false);

  const { count, reset } = useCounter(seconds, {
    min: 0,
    max: seconds,
  });

  const remainingTime = computed(() => count.value);


  const start = () => {
    if (isRunning.value) return;

    isRunning.value = true;
    reset(seconds);

    const timer = setInterval(() => {
      count.value--;

      if (count.value <= 0) {
        clearInterval(timer);
        isRunning.value = false;
        reset(seconds);
        onComplete?.();
      }
    }, 1000);
  };

  const stop = () => {
    isRunning.value = false;
    reset(seconds);
  };

  return {
    isRunning,
    remainingTime,
    start,
    stop,
  };
}
